<?php
/**
 * Markets Controller
 *
 * PHP version 5
 *
 * @category Controller
 * @package  Croogo
 * @version  1.0
 * @author   Tran Van Dung <dungtv@ic-t.info>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.croogo.org
 */
class MarketsController extends AppController {
/**
 * Controller name
 *
 * @var string
 * @access public
 */
    public $name = 'Markets';
/**
 * Models used by the Controller
 *
 * @var array
 * @access public
 */
    public $uses = array('Market', 'Bank', 'Country');
/**
 * Helpers used by the Controller
 *
 * @var array
 * @access public
 */
    public $helpers = array('Text', 'Html', 'Js');

    protected $paginate = array(
        'limit' => 10,
        );

/**
 * Before executing controller actions
 *
 * @return void
 * @access public
 */
    public function beforeFilter() {
        parent::beforeFilter();

        if ($this->action == 'add' || $this->action == 'edit' || $this->action == 'admin_add' || $this->action == 'admin_edit') {
            $this->Security->validatePost = false;
        }
    }

/**
 * Admin index
 *
 * @return void
 * @access public
 */
    public function admin_index() {
        $this->set('title_for_layout', __('MARKET LIST'));

        $this->Session->delete('cur_bank1s');
        $this->Session->delete('cur_bank2s');
        
        $this->Market->recursive = 0;
        $this->paginate['Market']['order'] = 'Market.name ASC';
        
        $windowMsg = false;
        if($this->params['action']=='admin_browse') {
            $windowMsg = true;
            $scriptWindowMsg = $this->windowMsg();
            $this->set('scriptWindowMsg', $scriptWindowMsg);
            
            $newest = $this->Market->find('first', array('fields' => array('Market.id', 'Market.name'), 'order' => array('Market.id DESC')));
            $this->set('newest', $newest);
        }
        $this->set('windowMsg', $windowMsg);
        
        $this->set('markets', $this->paginate());
    }

/**
 * Admin add
 *
 * @return void
 * @access public
 */
    public function admin_add() {
        $this->set('title_for_layout', __('MARKET DETAIL'));
        
        $redirect = array('action'=>'index');
        $rel = '';
        if(isset($this->params['named']['rel']) && $this->params['named']['rel']=='browse') {
            $rel = 'browse';
            $redirect = array('action'=>'browse');
        }
        if (!empty($this->request->data)) {
            $country = $this->Country->find('first', array('conditions' => array('name' => $this->request->data['Market']['country'])));
            if(!$country) {
                $country = array('name' => $this->request->data['Market']['country']);
                $this->Country->save($country);
            }
            
            $bank1Ids = array();
            $bank2Ids = array();
            $bank1 = false;
            $bank2 = false;
            if(isset($this->request->data['Bank'])) {
                foreach ($this->request->data['Bank'] as $bank) {
                    if($bank['t_bank']==1) {
                        $bank1 = true;
                        $bank1Ids[] = $bank['id'];
                    } elseif($bank['t_bank']==2) {
                        $bank2 = true;
                        $bank2Ids[] = $bank['id'];
                    }
                }
            }
            if(true) {
                unset($this->request->data['Bank']);
                $this->request->data['Market']['bank1'] = $this->Market->encodeData($bank1Ids);
                $this->request->data['Market']['bank2'] = $this->Market->encodeData($bank2Ids);
                $this->request->data['Market']['address'] = nl2br($this->request->data['Market']['address']);
                $this->Market->create();
                if ($this->Market->save($this->request->data)) {
                    $this->Market->lock($bank1Ids);
                    $this->Market->lock($bank2Ids);
                    //$this->Session->setFlash(__('The Market has been saved'), 'default', array('class' => 'success'));

                    $this->redirect($redirect);
                } else {
                    $bank1s = $this->Bank->find('list');
                    $bank2s = $bank1s;
                    $this->set(compact('bank1s'));
                    $this->set(compact('bank2s'));
                    $this->set('rel', $rel);
                    $this->Session->setFlash(__('The Market could not be saved. Please, try again.'), 'default', array('class' => 'error'));
                } 
            } else {
                $this->Session->setFlash(__('The Market could not be saved, at least two or more Bank in Market. Please, try again.'), 'default', array('class' => 'error'));
            }
        }
        
        $auto_complete = $this->jquery_auto_complete();
        $this->set('auto_complete', $auto_complete);
        
        $bank1s = $this->Bank->find('list');
        $bank2s = $bank1s;
        $this->set(compact('bank1s'));
        $this->set(compact('bank2s'));
        $this->set('rel', $rel);
    }

    public function jquery_auto_complete() {
        $countries = $this->Country->find('list', array('fields' => 'name'));
        $output = '
            $(function() {
                var availableCountries = ["'.implode('","', $countries).'"];
                $( "#MarketCountry" ).autocomplete({
                    source: availableCountries
                });
            });';
		return $output;
    }

    public function admin_add_bank1($id=null){
        $bank1s = $this->Bank->find('first', array('conditions' => array('Bank.id' => $id)));
        $this->set('bank1s', $bank1s);
        $this->layout = 'ajax';
    }
    
    public function admin_add_bank2($id=null){
        $bank2s = $this->Bank->find('first', array('conditions' => array('Bank.id' => $id)));
        $this->set('bank2s', $bank2s);
        $this->layout = 'ajax';
    }
    
    public function admin_delete_bank($id=null){
        $this->layout = 'ajax';
        $success = false;
        if($id != '') {
            $success = true;
        }
        $success = $this->Market->encodeData(array('success' => $success), array('json' => true, 'trim' => false));
        $this->set('success', $success);
    }
    
/**
 * Admin edit
 *
 * @param int $id 
 * @return void
 * @access public
 */
    public function admin_edit($id = null) {
        $this->set('title_for_layout', __('MARKET DETAIL'));

        $redirect = array('action'=>'index');
        $rel = '';
        if(isset($this->params['named']['rel']) && $this->params['named']['rel']=='browse') {
            $rel = 'browse';
            $redirect = array('action'=>'browse');
        }
        $this->set('rel', $rel);

        if (!$id && empty($this->request->data)) {
            $this->Session->setFlash(__('Invalid Market'), 'default', array('class' => 'error'));
            $this->redirect($redirect);
        }
        if (!empty($this->request->data)) {
            $country = $this->Country->find('first', array('conditions' => array('name' => $this->request->data['Market']['country'])));
            if(!$country) {
                $country = array('name' => $this->request->data['Market']['country']);
                $this->Country->save($country);
            }
            
            $bank1Ids = array();
            $bank2Ids = array();
            $bank1 = false;
            $bank2 = false;
            if(isset($this->request->data['Bank'])) {
                if(isset($this->request->data['Bank'])) {
                    foreach ($this->request->data['Bank'] as $bank) {
                        if($bank['t_bank']==1) {
                            $bank1 = true;
                            $bank1Ids[] = $bank['id'];
                        } elseif($bank['t_bank']==2) {
                            $bank2 = true;
                            $bank2Ids[] = $bank['id'];
                        }
                    }
                }
            }
            if(true) {
                unset($this->request->data['Bank']);
                $this->request->data['Market']['bank1'] = $this->Market->encodeData($bank1Ids);
                $this->request->data['Market']['bank2'] = $this->Market->encodeData($bank2Ids);
                $this->request->data['Market']['address'] = nl2br($this->request->data['Market']['address']);
                if ($this->Market->save($this->request->data)) {
                    $cur_bank1Ids = $this->Session->read('cur_bank1s');
                    $cur_bank2Ids = $this->Session->read('cur_bank2s');

                    $this->Market->lock($cur_bank1Ids, 'cc_banks', -1);
                    $this->Market->lock($cur_bank2Ids, 'cc_banks', -1);

                    $this->Market->lock($bank1Ids);
                    $this->Market->lock($bank2Ids);
                    //$this->Session->setFlash(__('The Market has been saved'), 'default', array('class' => 'success'));
                    $this->request->data = $this->Market->read(null, $id);
                    $bank1Ids = $this->Market->decodeData($this->request->data['Market']['bank1']);
                    $bank2Ids = $this->Market->decodeData($this->request->data['Market']['bank2']);

                    $bank1s = $this->Bank->find('list', array('conditions' => array('NOT' => array('Bank.id' => $bank1Ids))));
                    $bank2s = $this->Bank->find('list', array('conditions' => array('NOT' => array('Bank.id' => $bank2Ids))));
                    $this->set(compact('bank1s'));
                    $this->set(compact('bank2s'));

                    $cur_bank1s = $this->Bank->find('all', array('conditions' => array('Bank.id' => $bank1Ids)));
                    $cur_bank2s = $this->Bank->find('all', array('conditions' => array('Bank.id' => $bank2Ids)));
                    $this->set('cur_bank1s', $cur_bank1s);
                    $this->set('cur_bank2s', $cur_bank2s);
                    $this->redirect($redirect);
                } else {
                    $this->Session->setFlash(__('The Market could not be saved. Please, try again.'), 'default', array('class' => 'error'));
                }
            } else {
                $this->Session->setFlash(__('The Market could not be updated, at least two or more Bank in Market. Please, try again.'), 'default', array('class' => 'error'));
            }
        }
        if (empty($this->request->data)) {
            $this->request->data = $this->Market->read(null, $id);
            $bank1Ids = $this->Market->decodeData($this->request->data['Market']['bank1']);
            $bank2Ids = $this->Market->decodeData($this->request->data['Market']['bank2']);
            
            $this->Session->write('cur_bank1s', $bank1Ids);
            $this->Session->write('cur_bank2s', $bank2Ids);
            
            $bank1s = $this->Bank->find('list', array('conditions' => array('NOT' => array('Bank.id' => $bank1Ids))));
            $bank2s = $this->Bank->find('list', array('conditions' => array('NOT' => array('Bank.id' => $bank2Ids))));
            $this->set(compact('bank1s'));
            $this->set(compact('bank2s'));
            
            $cur_bank1s = $this->Bank->find('all', array('conditions' => array('Bank.id' => $bank1Ids)));
            $cur_bank2s = $this->Bank->find('all', array('conditions' => array('Bank.id' => $bank2Ids)));
            $this->set('cur_bank1s', $cur_bank1s);
            $this->set('cur_bank2s', $cur_bank2s);
            
            $auto_complete = $this->jquery_auto_complete();
            $this->set('auto_complete', $auto_complete);
        
        }
    }

/**
 * Admin delete
 *
 * @param int $id 
 * @return void
 * @access public
 */
    public function admin_delete($id = null) {
        
        $redirect = array('action'=>'index');
        $rel = '';
        if(isset($this->params['named']['rel']) && $this->params['named']['rel']=='browse') {
            $rel = 'browse';
            $redirect = array('action'=>'browse');
        }
        if (!$id) {
            $this->Session->setFlash(__('Invalid id'), 'default', array('class' => 'error'));
            $this->redirect($redirect);
        }

        $market = $this->Market->find('first', array(
            'conditions' => array(
                'id' => $id,
            ),
        ));
        if (isset($market['Market'])) {
            if($market['Market']['lock']<=0) {
                if ($this->Market->delete($id)) {
                    $this->Market->lock($this->Market->decodeData($this->request->data['Market']['bank1']), 'cc_banks', -1);
                    $this->Market->lock($this->Market->decodeData($this->request->data['Market']['bank2']), 'cc_banks', -1);
                    //$this->Session->setFlash(__('Market deleted'), 'default', array('class' => 'success'));
                    $this->redirect($redirect);
                }
            } else {
                $this->Session->setFlash(__('Market was locked'), 'default', array('class' => 'success'));
                $this->redirect(array('action'=>'index'));
            }
        } else {
            $this->Session->setFlash(__('Invalid id '), 'default', array('class' => 'error'));
            $this->redirect($redirect);
        }
    }
    public function admin_checkunique($id = '') {

        $this->layout = 'ajax';
        $success = false;
        if ($id != '' || $id != 'undefined') {
            $banks = $this->Market->find('first', array('fields' => array('Market.name'), 'conditions' => array('Market.name' => $id,)));
            if ($banks) {
                $success = true;
                $success = $this->Market->encodeData(array('success' => $success, 'isExsist' => '1'), array('json' => true, 'trim' => false));
            }else{
                $success = true;
                $success = $this->Market->encodeData(array('success' => $success, 'isExsist' => '0'), array('json' => true, 'trim' => false));
            }
        } else {
            $success = $this->Market->encodeData(array('success' => $success, 'isExsist' => '0'), array('json' => true, 'trim' => false));
        }
        $this->set('success', $success);
    }

    public function windowMsg() {
        $output = "
                $(function(){
                    // don't forget this init!      
                    $.initWindowMsg();

                    // upon click of a button, send corresponding text input value to parent window
                    $('.childButton').click(function(){
                        var childMsg = 'childMsgMarket'
                        var value = $(this).attr('title');
                        $.triggerParentEvent(childMsg, value); 
                        window.close();
                    });
                    
                    // auto add marker
                    var newest = $('#newest').val();
                    $.triggerParentEvent('childMsgMarket', newest); 
                    window.close();
                });";

        return $output;
    }

    public function admin_browse() {
        $this->layout = 'admin_full';
        $this->admin_index();
    }

}
?>